package cn.lei.netty.herostory;

import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * 广播员
 *
 * @author lil
 */
public final class BroadCaster {

    /**
     * 信道组,注意一定要是static,否则无法实现重发
     */
    private static final ChannelGroup CHANNEL_GROUP = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    /**
     * 私有化默认构造器
     */
    private BroadCaster() {

    }

    /**
     * 添加信道
     *
     * @param ch
     */
    public static void addChannel(Channel ch) {
        if (ch != null) {
            CHANNEL_GROUP.add(ch);
        }
    }


    /**
     * 移除信道
     *
     * @param ch
     */
    public static void removeChannel(Channel ch) {
        if (ch != null) {
            CHANNEL_GROUP.remove(ch);
        }

    }

    /**
     * 广播消息
     *
     * @param msg
     */
    public static void broadcast(Object msg) {
        if (msg != null) {
            CHANNEL_GROUP.writeAndFlush(msg);
        }
    }
}
